import os
import csv

class TestBedSpreadsheetWriter(object):
    '''
    classdocs
    '''


    def __init__(self, path="", fileName="", fieldNameList=[]):
        '''
        Constructor
        '''
        if path != "":
            self.Path = path
            
        if fileName != "":
            self.FileName = fileName
        if fieldNameList != []:
            self.FieldNameList = fieldNameList
        
    def Apply(self, expResults):
        if hasattr(self, "Path"):
            path = self.Path
        else:
            path = os.getcwd()
        
        fileName = ""
        if hasattr(self, "FileName"):
            fileName = self.FileName
        else:
            fileName = "ExperimentResults.tsv"
                
        fieldNameList = []
        if hasattr(self, "FieldNameList"):
            fieldNameList = self.FieldNameList
        

        fullPath = path + "\\" + fileName
        tsvFile = open(fullPath, 'wb')
        wr = csv.writer(tsvFile, delimiter='\t')
        
                
        resultKeyValueList = expResults.__dict__.items()
        resultKeyValueList.sort()
        
        #Remove fields that are not specified by fieldNameList
        for i in range(len(resultKeyValueList)-1, -1, -1):
            if fieldNameList != [] and not (resultKeyValueList[i][0] in fieldNameList):
                del resultKeyValueList[i]
        
        #Encapsulate all values in a list that are not already in a list.
        for i in range(0, len(resultKeyValueList)):
            if isinstance(resultKeyValueList[i][1], list) == False:
                    resultKeyValueList[i] = (resultKeyValueList[i][0], [resultKeyValueList[i][1]])

        firstTableDict = {}

        #Write all lists of non iterable values to a single table.
        for i in range(len(resultKeyValueList)-1, -1, -1):
            key, valueList = resultKeyValueList[i]
            if (not hasattr(valueList[0], "__iter__")):
                firstTableDict[key] = valueList
                del resultKeyValueList[i]
            elif isinstance(valueList[0], set):
                for j in range(0, len(valueList)):
                    valueList[j] = list(valueList[j])
                    valueList[j].sort()
                firstTableDict[key] = valueList
                del resultKeyValueList[i]
                                
        firstTableKeys = firstTableDict.keys()
        firstTableKeys.sort()
        
        #Write first title row
        wr.writerow(firstTableKeys)
            
        allDataWritten = True
        rowIndex = 0
        
        while True:
            curRow = []
            for key in firstTableKeys:
                curList = firstTableDict[key]
                if len(curList) <= rowIndex:
                    curRow.append("")
                else:
                    curRow.append(curList[rowIndex])
                    allDataWritten = False
                
            if allDataWritten == True:
                break 
            
            wr.writerow(curRow)
            
            allDataWritten = True
            rowIndex += 1
        
        
        
        
        #Write each of the remaining fields to their own table.       
        for fieldName, valueList in resultKeyValueList:
            wr.writerow([""])
            wr.writerow([fieldName])
            
            firstIterValue = valueList[0]
            keyList = []
            
            if isinstance(firstIterValue, dict):
                keySet = set([])
                for curDict in valueList:
                    keySet = keySet.union(curDict.keys())
                
                keyList = list(keySet)
                keyList.sort()
                wr.writerow(keyList)
                
            elif isinstance(firstIterValue, list):
                longestList = 0
                for curList in valueList:
                    if len(curList) > longestList:
                        longestList = len(curList)
                keyList = range(0, longestList)
            else:
                print("Unknown iterable type: " + str(type(firstIterValue)))
                continue
            
            for iterValue in valueList:
                curRow = []
                for key in keyList:
                    curVal = ""
                    try:
                        curVal = iterValue[key]
                    except Exception:
                        pass
                    curRow.append(curVal)
                wr.writerow(curRow)
        
        tsvFile.close()
                